#!/bin/bash

# Author: Turing Zhu<qishiwenjun@163.com>
# Date: 2018-06-13 17:37:27
# Desc: start jar
#

# error code
# 1: missing parameter
# 2: not a jar file
# 3: start jar file failed

TIMEOUT=180  # 3 minutes timeout

function print_help() {
    cat <<EOF
Usage:      $0 jarfile
Example:    $0 abc.jar

EOF
}


function echo_error() {
    printf "[ \033[31mERROR $1\033[0m ] $2\n"
}

function main() {
	# check parameter
	if [[ $# -lt 1 ]];then
		echo_error 1 "missing parameter"
		print_help
		exit 1
	fi
	
	# check file type
	local jarfile=$1
	local extension=${jarfile##*.}
	if [[ $extension != jar ]];then
		echo_error 2 "not a jar file"
		exit 2
	fi

	# check process is running
	local pid=$(ps -ef|grep -E "\-jar $jarfile" | grep -v grep |awk '{print $2}')
	if [[ "$pid" != "" ]];then
		ps -ef|grep -E "\-jar $jarfile" | grep -v grep
		printf "[ \033[33mWARNING\033[0m ] a process $pid of $jarfile is running.\n"
		printf "    the $0 $jarfile is canceled or rerun restart.sh $jarfile\n"
		exit 0
	fi
	  local fileName=$(basename $jarfile .jar)
    local logFile="/home/services/logs/"$fileName"/"$fileName".log"

	# clear log
	
	printf "" > $logFile

	# start jar file
	java -Xms100M -Xmx100M -jar $jarfile &

	# check starting result
	local count=0
	echo ""
	while true;do
		grep -q 'Started' $logFile
		[[ $? -eq 0 ]] && break
		((count++))
		if [[ $count -ge $TIMEOUT ]];then
			echo_error 3 "start faild, please check log file "
			exit 3
		fi
		echo -ne "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\bUSING TIME $count SECONDS..."
		sleep 1
	done
	printf "\n\033[32m START $jarfile SUCCESS! using time $count seconds \n\033[0m"
}


main $*
